package com.ls.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.config.satoken.SaTokenUtilPy;
import com.ls.controller.customer.model.TimeModel;
import com.ls.controller.smsrecord.model.QuertSmsRecordModel;
import com.ls.controller.smsrecord.model.SmsDataModel;
import com.ls.controller.smsrecord.model.SmsRecordModel;
import com.ls.entity.Holiday;
import com.ls.entity.SmsRecord;
import com.ls.entity.Customer;
import com.ls.entity.SmsTemplate;
import com.ls.enums.CallTypeEnum;
import com.ls.enums.SendStatusEnum;
import com.ls.mapper.SmsRecordMapper;
import com.ls.service.IHolidayService;
import com.ls.service.ISmsRecordService;
import com.ls.enums.RoleEnum;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.utils.ResultData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.ls.constant.SystemConstants.*;

/**
 * <p>
 * 短信记录表 服务实现类
 * </p>
 *
 * @author pengyu
 * @since 2024-10-06
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class SmsRecordServiceImpl extends ServiceImpl<SmsRecordMapper, SmsRecord> implements ISmsRecordService {
    private final IHolidayService holidayService;

    /**
     * 查询短信列表
     */
    @Override
    public ResultData pageList(SmsRecordModel model) {
        log.info("查询短信列表pageList:{}", model);
        Customer customer = SaTokenUtilPy.getCustomer();
        Long id = null;
        if (!RoleEnum.ADMIN.equals(customer.getRoleId())) {
            id = customer.getCustomerId();
        }
        List<Long> holidayIds = new ArrayList<>();
        if (model.getCategoryId() != null) {
            List<Holiday> holidayList = new ArrayList<>();
            if (model.getCategoryId() == 1) {
                holidayList = holidayService.list(new LambdaQueryWrapper<Holiday>()
                        .in(Holiday::getCategoryId, Arrays.asList(1, 2, 3, 4))
                        .eq(Holiday::getValidFlag, VALID_TRUE)
                        .orderByDesc(Holiday::getCreateTime)
                );
                log.info("获取所有节假日id:{}", holidayIds);
            } else if (model.getCategoryId() == 2) {
                holidayIds.add(6L);
            } else {
                holidayList = holidayService.list(new LambdaQueryWrapper<Holiday>()
                        .eq(Holiday::getCategoryId, model.getCategoryId())
                        .eq(Holiday::getValidFlag, VALID_TRUE)
                        .orderByDesc(Holiday::getCreateTime)
                );
            }
            if (model.getCategoryId() != 2) {
                holidayIds = Optional.ofNullable(holidayList)
                        .orElse(Collections.emptyList())
                        .stream()
                        .map(Holiday::getHolidayId)
                        .collect(Collectors.toList());
            }
        }
        LambdaQueryWrapper<SmsRecord> wrapper = new LambdaQueryWrapper<SmsRecord>()
//                .eq(SmsRecord::getSmsStatus, SMS_STATUS_TRUE)
                .eq(id != null, SmsRecord::getCustomerId, id)
                .eq(model.getTemplateCategory() != null, SmsRecord::getTemplateCategory, model.getTemplateCategory())
                .ge(StringUtils.isNotBlank(model.getStartTime()), SmsRecord::getCreateTime, model.getStartTime())
                .le(StringUtils.isNotBlank(model.getEndTime()), SmsRecord::getCreateTime, model.getEndTime())
                .orderByDesc(SmsRecord::getCreateTime);
        if (model.getTemplateCategory() != null) {
            if (model.getTemplateCategory() == TEMPLATE_CATEGORY_CARE) {
                wrapper.eq(model.getHolidayId() != null, SmsRecord::getHolidayId, model.getHolidayId())
                        .in(model.getCategoryId() != null && holidayIds.size() > 0, SmsRecord::getHolidayId, holidayIds)
                        .eq(model.getCategoryId() != null && holidayIds.size() == 0, SmsRecord::getHolidayId, -1);
            } else if (model.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP) {
                wrapper.eq(model.getCallType() != null, SmsRecord::getCallType, model.getCallType());
            }
        }
        log.info("查询短信列表条件:{}", wrapper);
        Page page = new Page(model.getPageNum(), model.getPageSize());
        IPage<SmsRecord> dtoIPage = this.baseMapper.selectPage(page, wrapper);
        // 新增类型名称映射
        dtoIPage.getRecords().forEach(record -> {
            if (record.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP){
                record.setSmsTypeName(CallTypeEnum.getRoleName(record.getCallType()));
            } else if (record.getTemplateCategory() == TEMPLATE_CATEGORY_CARE) {
                record.setSmsTypeName(holidayService.getById(record.getHolidayId()).getHolidayName());
            }else {
                record.setSmsTypeName("");
            }
        });
        log.info("查询短信列表结果:{}", dtoIPage);
        return ResultData.successData(dtoIPage);
    }

    /**
     * PC查询短信列表
     */
    @Override
    public ResultData getPaging(QuertSmsRecordModel model) {
        log.info("查询短信列表getPaging:{}", model);
        List<Long> holidayIds = Collections.emptyList();
        if (model.getTemplateCategory() != null) {
            if (model.getTemplateCategory() == TEMPLATE_CATEGORY_CARE) {
                List<Holiday> holidayList = holidayService.list(new LambdaQueryWrapper<Holiday>()
                        .eq(model.getCategoryId() != null, Holiday::getCategoryId, model.getCategoryId())
                        .eq(Holiday::getValidFlag, VALID_TRUE)
                        .orderByDesc(Holiday::getCreateTime)
                );
                // 提取节日ID集合
                holidayIds = ((List<Holiday>) holidayList).stream()
                        .map(Holiday::getHolidayId)
                        .collect(Collectors.toList());
            }
        }
        LambdaQueryWrapper<SmsRecord> wrapper = new LambdaQueryWrapper<SmsRecord>()
                .like(model.getCustomerPhone() != null, SmsRecord::getCustomerPhone, model.getCustomerPhone())
                .like(model.getOuterPhone() != null, SmsRecord::getOuterPhone, model.getOuterPhone())
                .eq(model.getSmsStatus() != null, SmsRecord::getSmsStatus, model.getSmsStatus())
                .eq(model.getTemplateCategory() != null, SmsRecord::getTemplateCategory, model.getTemplateCategory())
                .between(model.getStartTime() != null && model.getEndTime() != null, SmsRecord::getCreateTime, model.getStartTime(), model.getEndTime())
                .orderByDesc(SmsRecord::getCreateTime);
        if (model.getTemplateCategory() != null) {
            if (model.getTemplateCategory() == TEMPLATE_CATEGORY_CARE) {
                wrapper.eq(model.getHolidayId() != null, SmsRecord::getHolidayId, model.getHolidayId())
                        .in(model.getTemplateCategory() != null && holidayIds.size() > 0, SmsRecord::getHolidayId, holidayIds)
                        .eq(model.getTemplateCategory() != null && holidayIds.size() == 0, SmsRecord::getHolidayId, -1);
            } else if (model.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP) {
                wrapper.eq(model.getCallType() != null, SmsRecord::getCallType, model.getCallType());
            } else if (model.getTemplateCategory() == TEMPLATE_CATEGORY_LOGISTICS) {
                wrapper.eq(model.getSendStatus() != null, SmsRecord::getSendStatus, model.getSendStatus());
            }
        } else {
//            wrapper.in(SmsRecord::getTemplateCategory, Arrays.asList(0, 1,3));
            wrapper.ne( SmsRecord::getTemplateCategory, TEMPLATE_CATEGORY_LOGISTICS);
        }
        log.info("查询短信列表条件:{}", wrapper);
        Page page = new Page(model.getPageNum(), model.getPageSize());
        IPage<SmsRecord> dtoIPage = this.baseMapper.selectPage(page, wrapper);
        log.info("查询短信列表结果:{}", dtoIPage);
        dtoIPage.getRecords().forEach(record -> {
            if (record.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP){
                record.setSmsTypeName(CallTypeEnum.getRoleName(record.getCallType()));
            } else if (record.getTemplateCategory() == TEMPLATE_CATEGORY_CARE) {
                record.setSmsTypeName(holidayService.getById(record.getHolidayId()).getHolidayName());
            }else if (record.getTemplateCategory() == TEMPLATE_CATEGORY_LOGISTICS){
                record.setSmsTypeName(SendStatusEnum.getSendStatusName(record.getSmsStatus()));
            }else {
                record.setSmsTypeName("预定短信");
            }
        });
        return ResultData.successData(dtoIPage);
    }

    /**
     * 统计信息短信量
     */
    @Override
    public ResultData getDataSms(TimeModel model) {
        //统计每个呼出类型的短信量
        List<SmsRecord> records = list(new LambdaQueryWrapper<SmsRecord>()
                .eq(SmsRecord::getSmsStatus, SMS_STATUS_TRUE)
                .between(StringUtils.isNotBlank(model.getBeginSt()), SmsRecord::getSendTime, model.getBeginSt()+ " 00:00:00", model.getEndSt()+ " 23:59:59")
        );
        // 按产品类型和周期双重分组统计
        Map<Integer, Long> smsCounts = records.stream()
                .filter(record -> record.getCallType() != null)
                .collect(Collectors.groupingBy(
                        SmsRecord::getCallType,
                        Collectors.counting()
                ));

        // 组装返回数据结构
        List<SmsDataModel> result = new ArrayList<>();
        smsCounts.forEach((callType, count) -> {
//            呼入： 1 拒接 2 未接通 3 已接通 4勿扰；  呼出：5 所有
            result.add(new SmsDataModel(CallTypeEnum.getRoleName(callType), count));
        });
        return ResultData.successData(result);
    }
}
